package com.jiu.http.webqq;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
import javax.script.ScriptEngine;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import com.jiu.core.Account;
import com.jiu.core.FishClient;
import com.jiu.util.JSONUtils;
import com.jiu.util.JavaScriptUtils;

public class QQHttp {
	private final String WEBQQ_APPID = "1003903";
	private FishClient context;
	private QQSession session;
	public QQSession getSession() {
		return session;
	}

	private String group_uin;
	private int num;
	private String group_code;
	public QQHttp(FishClient context) {
		this.context = context;
		this.session = new QQSession();
		init();
	}

	public void init() {
		try {
			loginOne();
			webqqLogin2();
			findGroupUin(context.getAccount().getControlGroup());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	private void loginOne() throws Exception {
		Account account = context.getAccount();
		String qq = account.getProxyQQ();
		String pwd = account.getProxyPwd();
		if(account.getControlGroup().equals("盒子里有鱼")
				||account.getControlGroup().equals("我的青春我做主")
				||account.getControlGroup().equals("自由")
				||account.getControlGroup().equals("小星星")){
			
				Map<String,String> checkMap =  getConnection(getcheckUrl(qq), "");
				String[] data = dearWithReturnInfo(checkMap.get("message"));	
				String loginUrl = "",cookie=checkMap.get("cookie");
				if(data[0].equals("0")){
				    loginUrl = getLoginUrl(qq, pwd, data[1],data[2]);
				}else{
				    //弹出验证码
				    Map<String,Object> imgInfo = getImage(getImgUrl(qq));
				    cookie = (String) imgInfo.get("cookie");
				    String vcode = JOptionPane.showInputDialog(context.getMainFrame(),(ImageIcon)imgInfo.get("image")).toUpperCase();
				    loginUrl = getLoginUrl(qq, pwd, vcode,data[2]);					    
				}
				//登录
				Map<String,String> baseLoginMap = getConnection(loginUrl, cookie);
				session.setCheck_sigURL(dearWithReturnInfo(baseLoginMap.get("message"))[2]);
				session.setWebqqcookie(baseLoginMap.get("cookie"));
				baseLoginMap.put("cookie", dearWithCookie(baseLoginMap.get("cookie")));
				if(!baseLoginMap.get("message").contains("登录成功"))					
					JOptionPane.showMessageDialog(context.getMainFrame(),"登录失败，请重试！");	
		}else{
			JOptionPane.showMessageDialog(context.getMainFrame(),"非法监控群，请联系作者！");
		}
}

	@SuppressWarnings("unchecked")
	private void webqqLogin2() throws Exception {
		Map<String,String> loginMap = getConnection(session.getCheck_sigURL(), session.getWebqqcookie());
		String content = "r=%7B%22status%22%3A%22hidden%22%2C%22ptwebqq%22%3A%22"+session.getPtwebqq()+"%22%2C%22passwd_sig%22%3A%22%22%2C%22clientid%22%3A%22"+session.getClientId()+"%22%2C%22psessionid%22%3Anull%7D&clientid="+session.getClientId()+"&psessionid=null";
		//webqq基础cookie
		session.setWebqqcookie(dearWithCookie(loginMap.get("cookie"))+"ptwebqq="+session.getPtwebqq()+";");
		String webqqLoginInfo = postConnection("http://d.web2.qq.com/channel/login2",content,session.getWebqqcookie());
		Map<String,Object> webqqLoginMap = JSONUtils.parseMap(webqqLoginInfo);
		Map<String,Object> result = (Map<String,Object>)webqqLoginMap.get("result");
		session.setPsessionid(result.get("psessionid").toString());
		session.setVfwebqq(result.get("vfwebqq").toString());
	}
	
	@SuppressWarnings("unchecked")
	private void findGroupUin(String name) throws Exception {
		String groupUrl ="http://s.web2.qq.com/api/get_group_name_list_mask2";
		//groupContent = {"hash":"0505070306560103530752540402545404515702065404020157010201530B030A500A070102050A570306555656025607005607575601045507005050000A0244564145455D4156125145405940","vfwebqq":"c52798bb09647d8a6af86d5c509f137f336c858c1ab2cadedecb4082dfc66cde8551fbf44f86cec2"}
		String groupContent = "r=%7B%22hash%22%3A%22"+session.getHash()+"%22%2C%22vfwebqq%22%3A%22"+session.getVfwebqq()+"%22%7D";
		String groupInfo = postConnection(groupUrl, groupContent, session.getWebqqcookie());
		Map<String, Object> groupMap = JSONUtils.parseMap(groupInfo);
		Map<String,Object> groupResult  =(Map<String,Object>)groupMap.get("result");
		List<Map<String,Object>> groupList = (List<Map<String, Object>>) groupResult.get("gnamelist");
		for(Map<String,Object> map:groupList){
			if(map.get("name").toString().equals(name)){
				 this.group_uin = map.get("gid").toString();
				 this.group_code = map.get("code").toString();
			}
			
		}
		
	}
	
	//接消息方法
	public String webQQpoll2() throws Exception {
		final String poll2Url = "http://d.web2.qq.com/channel/poll2";
		final String poolContent = "r=%7B%22clientid%22%3A%22"+session.getClientId()
				+"%22%2C%22psessionid%22%3A%22" +session.getPsessionid()
				+"%22%2C%22key%22%3A0%2C%22ids%22%3A%5B%5D%7D&clientid="+session.getClientId()
				+"&psessionid="+session.getPsessionid();
		return postConnection(poll2Url,poolContent, session.getWebqqcookie());
	}
	/**
	 * 回复消息
	 * */


	public void sendMessage(String sendMsg) throws Exception {
		String sendUrl = "http://d.web2.qq.com/channel/send_qun_msg2";
		String sendCookie = session.getWebqqcookie()+";pgv_pvid=8631489889; pgv_flv=11.8 r800;";
		String sendContent = "r=%7B%22group_uin%22%3A"+group_uin+"%2C%22content%22%3A%22%5B%5C%22"+
				URLEncoder.encode(sendMsg,"utf-8")+"%5C%22%2C%5B%5C%22font%5C%22%2C%7B%5C%22name%5C%22%3A%5C%22%E5%AE%8B%E4%BD%93%5C%22%2C%5C%22size%5C%22%3A%5C%22"+9+"%5C%22%2C%5C%22style%5C%22%3A%5B0%2C0%2C0%5D%2C%5C%22color%5C%22%3A%5C%22"+context.getAccount().getQqColor()+"%5C%22%7D%5D%5D%22%2C%22msg_id%22%3A"+
				context.getAccount().getProxyQQ().substring(0,4)+String.format("%04d",++this.num)+"%2C%22clientid%22%3A%22"+session.getClientId()+"%22%2C%22psessionid%22%3A%22"+session.getPsessionid()+"%22%7D&clientid="+session.getClientId()+"&psessionid="+session.getPsessionid();
		postMessage(sendUrl,sendContent,sendCookie);		
	}
	
	@SuppressWarnings("unchecked")
	public void updatePtwebqq() throws Exception{
		String content = "r=%7B%22status%22%3A%22hidden%22%2C%22ptwebqq%22%3A%22"+session.getPtwebqq()+"%22%2C%22passwd_sig%22%3A%22%22%2C%22clientid%22%3A%22"+session.getClientId()+"%22%2C%22psessionid%22%3Anull%7D&clientid="+session.getClientId()+"&psessionid=null";
		session.setWebqqcookie(session.getWebqqcookie().substring(0, session.getWebqqcookie().indexOf("ptwebqq"))+"ptwebqq="+session.getPtwebqq()+";");
		String webqqLoginInfo = postConnection("http://d.web2.qq.com/channel/login2",content,session.getWebqqcookie());
		Map<String,Object> webqqLoginMap = JSONUtils.parseMap(webqqLoginInfo);
		Map<String,Object> result = (Map<String,Object>)webqqLoginMap.get("result");
		session.setPsessionid(result.get("psessionid").toString());
		session.setVfwebqq(result.get("vfwebqq").toString());
	}
	
	public String dearWithCookie(String cookie){
		Pattern pattern = Pattern.compile("\\S*=$");
		String c = "";
		String[]data = cookie.split(";");
		for(int i=0;i<data.length;i++){
			Matcher matcher = pattern.matcher(data[i]);
        	if(matcher.find())continue;
			if(data[i].contains("PATH")||data[i].contains("EXPIRES")||data[i].contains("DOMAIN"))continue;
			if(data[i].contains("ptwebqq")) session.setPtwebqq(data[i].substring(8,data[i].length()));
			c += (data[i]+";");
		}
		try {
			ScriptEngine engine = JavaScriptUtils.getScriptEngine();
			String str = "'"+context.getAccount().getProxyQQ()+"','"+session.getPtwebqq()+"'";
			session.setHash((String)engine.eval("hash("+str+")"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return c;
	}
	
	public String[] dearWithReturnInfo(String info){
		int start = info.indexOf("(")+1;
		int end = info.indexOf(")");
		return info.substring(start, end).replace("'","").split(",");
	}
	
	
	
	
	
	@SuppressWarnings("static-access")
	public static Map<String, String> getConnection(String url, String cookie)
			throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		URL getUrl = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) getUrl.openConnection();
		conn.setRequestMethod("GET");// "POST" ,"GET"
		conn.setFollowRedirects(false);
		conn.addRequestProperty("Cookie", cookie);
		conn.addRequestProperty("Accept-Charset", "UTF-8;");// GB2312,
		conn.addRequestProperty("User-Agent",
				"Mozilla/5.0 (Windows NT 6.1; rv:23.0) Gecko/20100101 Firefox/23.0");
		conn.connect();
		String cooki = "";
		if (conn.getHeaderFields().get("Set-Cookie") != null) {
			for (String s : conn.getHeaderFields().get("Set-Cookie")) {
				cooki += s;
			}
		}
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				conn.getInputStream(), "utf-8"));
		String lines, str = "";
		while ((lines = reader.readLine()) != null) {
			str += lines;
		}
		reader.close();
		conn.disconnect();
		map.put("cookie", cooki);
		map.put("message", str);
		return map;
	}

	public static String getMessage(String url, String cookie) throws Exception {
		URL getUrl = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) getUrl.openConnection();
		conn.setRequestMethod("GET");// "POST" ,"GET"
		conn.addRequestProperty("Cookie", cookie);
		conn.addRequestProperty("Cache-Control", "no-cache");
		conn.addRequestProperty("Accept-Encoding", "gzip, deflate");
		conn.addRequestProperty("Accept-Charset", "UTF-8;");// GB2312,
		conn.addRequestProperty("Referer",
				"http://s.web2.qq.com/proxy.html?v=20110412001&callback=1&id=3");
		conn.addRequestProperty("User-Agent",
				"Mozilla/5.0 (Windows NT 6.1; rv:23.0) Gecko/20100101 Firefox/23.0");
		conn.connect();

		BufferedReader reader = new BufferedReader(new InputStreamReader(
				conn.getInputStream(), "utf-8"));
		String lines, str = "";
		while ((lines = reader.readLine()) != null) {
			str += lines;
		}
		reader.close();
		conn.disconnect();
		return str;
	}

	public static String postConnection(String url, String context,
			String cookie) throws IOException {
		URL postUrl = new URL(url);
		HttpURLConnection connection = (HttpURLConnection) postUrl
				.openConnection();
		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setRequestMethod("POST");
		connection
				.addRequestProperty("User-Agent",
						"Mozilla/5.0 (Windows NT 6.1; rv:24.0) Gecko/20100101 Firefox/24.0");
		connection.addRequestProperty("Charset", "utf-8");
		connection
				.addRequestProperty("Referer",
						"http://d.web2.qq.com/proxy.html?v=20110331002&callback=1&id=2");
		connection.addRequestProperty("Cache-Control", "no-cache");
		connection.addRequestProperty("Cookie", cookie);
		connection.setConnectTimeout(60000);
		connection.setReadTimeout(100000);
		connection.connect();
		DataOutputStream out = new DataOutputStream(
				connection.getOutputStream());
		out.writeBytes(context);
		out.flush();
		out.close(); // flush and close
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				connection.getInputStream(), "utf-8"));
		String line, str = "";
		while ((line = reader.readLine()) != null) {
			str += line;
		}
		reader.close();
		connection.disconnect();
		return str;
	}

	public static String postMessage(String url, String context, String cookie)
			throws Exception {
		String line, str = "";
		URL postUrl = new URL(url);
		HttpURLConnection connection = (HttpURLConnection) postUrl
				.openConnection();
		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setRequestMethod("POST");
		connection
				.addRequestProperty("User-Agent",
						"Mozilla/5.0 (Windows NT 6.1; rv:24.0) Gecko/20100101 Firefox/24.0");
		connection
				.addRequestProperty("Accept",
						"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		connection.addRequestProperty("Accept-Language",
				"zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
		connection.addRequestProperty("Accept-Encoding", "gzip, deflate");
		connection.addRequestProperty("Content-Type",
				"application/x-www-form-urlencoded; charset=UTF-8");
		connection
				.addRequestProperty("Referer",
						"http://d.web2.qq.com/proxy.html?v=20110331002&callback=1&id=2");
		connection.addRequestProperty("Pragma", "no-cache");
		connection.addRequestProperty("Cache-Control", "no-cache");
		connection.addRequestProperty("Cookie", cookie);
		connection.setConnectTimeout(10000);
		connection.setReadTimeout(30000);
		connection.connect();
		DataOutputStream out = new DataOutputStream(
				connection.getOutputStream());
		out.writeBytes(context);
		out.flush();
		out.close(); // flush and close
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				connection.getInputStream(), "utf-8"));
		while ((line = reader.readLine()) != null) {
			str += line;
		}
		reader.close();
		connection.disconnect();
		return str;
	}


	public static Map<String, Object> getImage(String url) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		URL getUrl = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) getUrl.openConnection();
		conn.connect();
		String cooki = "";
		if (conn.getHeaderFields().get("Set-Cookie") != null) {
			for (String s : conn.getHeaderFields().get("Set-Cookie")) {
				cooki += s;
			}
		}
		map.put("image", new ImageIcon(ImageIO.read(conn.getInputStream())));
		map.put("cookie", cooki);
		conn.disconnect();
		return map;
	}

	/**
	 * getUrl
	 * */
	private String getcheckUrl(String qq) {
		return "http://check.ptlogin2.qq.com/check"
				+ "?uin="
				+ qq
				+ "&appid="
				+ WEBQQ_APPID
				+ "&js_ver=10048&js_type=0&u1=http%3A%2F%2Fweb2.qq.com%2Floginproxy.html&r="
				+ Math.random();
	}

	private String getImgUrl(String qq) {
		return "http://captcha.qq.com/getimage?uin=" + qq + "&aid=" + WEBQQ_APPID
				+ "&r=" + Math.random();
	}

	private String getLoginUrl(String qq, String password, String vCode,
			String uin) throws Exception {
		ScriptEngine engine = JavaScriptUtils.getScriptEngine();
		String str = "'" + password + "','" + uin + "','" + vCode + "'";
		String p = (String) engine.eval("getpassword(" + str + ")");
		return "http://ptlogin2.qq.com/login?u="
				+ qq
				+ "&p="
				+ p
				+ "&verifycode="
				+ vCode.replace("'", "")
				+ "&webqq_type=10&remember_uin=1&login2qq=0&aid=1003903&u1=http%3A%2F%2Fweb2.qq.com%2Floginproxy.html%3Flogin2qq%3D1%26webqq_type%3D10&h=1&ptredirect=0&ptlang=2052&daid=164&from_ui=1&pttype=1&dumy=&fp=loginerroralert&action=9-23-835629&mibao_css=m_webqq&t=1&g=1&js_type=0&js_ver=10048";
	}

	public String getGroup_code() {
		return group_code;
	}

}
